package com.cloud.code.牛客网;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Queue;
import java.util.LinkedList;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        if (pRoot == null){
                return new ArrayList<>();
            }
            boolean preorder =true;
            ArrayList<ArrayList<Integer>> resultList = new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(pRoot);
            while (!queue.isEmpty()){
                ArrayList<Integer> levelList = new ArrayList<>();
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode poll = queue.poll();
                    levelList.add(poll.val);
                    if (poll.left != null){
                        queue.add(poll.left);
                    }
                    if (poll.right != null){
                        queue.add(poll.right);
                    }
                }
                resultList.add(levelList);
            }
            for (int i = 0; i < resultList.size(); i++) {
                if (!preorder){
                    Collections.reverse(resultList.get(i));
                }
                preorder = !preorder;
            }
            return resultList;
    }

}